package com.suzhe.ymall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhe.ymall.common.enums.StatusEnum;
import com.suzhe.ymall.system.pojo.SysUser;
import com.suzhe.ymall.system.mapper.SysUserMapper;
import com.suzhe.ymall.system.pojo.SysUserRole;
import com.suzhe.ymall.system.service.ISysUserRoleService;
import com.suzhe.ymall.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author suzhe
 * @since 2019-06-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    ISysUserRoleService iSysUserRoleService;
    @Override
    public void saveUser(SysUser sysUser) {
        Integer id = sysUser.getId();
        Date curDate = new Date();
        if (id == null) {
            sysUser.setUpdateTime(curDate);
            sysUser.setCreateTime(curDate);
            sysUser.setStatus(StatusEnum.ENABLE.getCode());
            save(sysUser);
        } else {
            iSysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",id));
            updateById(sysUser);
        }
        List<Integer> roleIds = sysUser.getRoleIds();
        if (roleIds != null && !roleIds.isEmpty()){
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            roleIds.forEach(item -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(id);
                sysUserRole.setRoleId(item);
                sysUserRole.setCreateTime(curDate);
                sysUserRoles.add(sysUserRole);
            });
            iSysUserRoleService.saveBatch(sysUserRoles);
        }
    }
}
